package com.atguigu.auth.service.Impl;

import com.atguigu.auth.service.SysMenuService;
import com.atguigu.auth.service.SysUserService;
import com.atguigu.model.system.SysUser;
import com.atguigu.security.custom.CustomUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: UserDetailsServiceImpl
 * Package: com.atguigu.auth.service.Impl
 * Description:
 *
 * @Author 蹇泽阳
 * @Create 2023/11/20 8:48
 * @Version 1.0
 */

@Component
public class UserDetailsServiceImpl implements UserDetailsService {
  
  @Autowired
  private SysUserService sysUserService;
  
  @Autowired
  private SysMenuService sysMenuService;
  
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(SysUser::getUsername, username);
    SysUser sysUser = sysUserService.getOne(wrapper);
    if(null == sysUser) {
      throw new UsernameNotFoundException("用户名不存在！");
    }
    
    if(sysUser.getStatus().intValue() == 0) {
      throw new RuntimeException("账号已停用");
    }
    // 根据用户id获取用户可以操作的按钮权限数据
    List<String> userpermsList = sysMenuService.findUserPermsByUserId(sysUser.getId());
    List<SimpleGrantedAuthority> authorities = new ArrayList<>();// 转换成SimpleGrantedAuthority格式
    for (String perm : userpermsList) {
      authorities.add(new SimpleGrantedAuthority(perm.trim()));
    }
    return new CustomUser(sysUser, authorities);
  }
}
